import os
import cv2
import time
import numpy as np
import pickle

import requests
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;0"

# Camera rtsp url goes here
# Refer to camera manual for detail on rtsp url
RTSP = "rtsp://admin:Aa123456@192.168.1.2:554/onvif1"

# server url to send image
SERVER_URL = "http://127.0.0.1:5000/receive-frame"


def generateSingleFrame(sleep_second=5):
    """
    generate single frame every x second
    :param sleep_second:
    :return: serialized numpy array
    """
    vcap = cv2.VideoCapture(RTSP)
    fps = vcap.get(cv2.CAP_PROP_FPS)

    # number of frame need to skip
    # for x frame per second
    skip_frame = fps*sleep_second

    count = 0
    while (1):
        # Capture frame-by-frame
        ret, frame = vcap.read()
        count += 1
        if count > skip_frame:
            frame: np.ndarray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
            # frame_byte: bytes = bytes(frame)
            serialized = pickle.dumps(frame, protocol=0)
            yield serialized
            count = 0
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        # time.sleep(sleep_second - time.time() + start_time)


def send_frame(url, frame_serialized):
    """
    :param url:  full url of server to receive image
    :param frame_serialized: created by pickle.dumps(frame, protocol=0)
    :return: 
    """
    name_img = "frame.png"
    files = {'image': (name_img, frame_serialized, 'multipart/form-data', {'Expires': '0'})}
    with requests.Session() as s:
        r = s.post(url, files=files)
        print("status ", r.status_code)
        return r


if __name__ == "__main__":
    iter_frame = generateSingleFrame(5)
    for frame in iter_frame:
        print("got a frame")
        resp = send_frame(SERVER_URL, frame)
        print("resp ", resp)
